<script lang="ts" setup>
import { reactive, ref, onMounted,nextTick } from "vue";
import {
  addRole,
  getRole,
  deleteRole,
  putRole,
  getResources,
  getRoleResources,
  putRoleResources
} from "@/api/index";
import inputtext from "@/components/inputs/inputtext.vue";
import inputradio from "@/components/inputs/inputradio.vue";
import { FormInstance, FormRules,TreeInstance } from "element-plus";
import { useRoute } from "vue-router";
const route = useRoute();
onMounted(() => {
  getData();
});

//#region  表格
const tableData: any[] = reactive([]);
const selectRow: any[] = reactive([]);
const getSelectionRows = function (e: any) {
  selectRow.length = 0
  selectRow.push(...e);
};

//#endregion

//#region 新增
const addshow = ref(false);
const formref = ref<FormInstance>();
interface Ruleform {
  rolename: string;
  status: 1 | 2;
  remark: string;
  description: string;
}
const form = reactive<Ruleform>({
  rolename: "",
  status: 1,
  remark: "",
  description: "",
});

const rules = reactive<FormRules<Ruleform>>({
  rolename: [{ required: true, message: "必填项", trigger: "blur" }],
  status: [{ required: true, message: "必填项", trigger: "blur" }],
  remark: [{ required: true, message: "必填项", trigger: "blur" }],
});

const addData = async function (formref: FormInstance | undefined) {
  if (!formref) return;
  await formref.validate((valid) => {
    if (valid) {
      addshow.value = false;
      const data = {
        rolename: form.rolename,
        remark: form.remark,
        status: form.status,
        description: form.description,
      };
      addRole(data).then((res) => {
        console.log(res.data);
        getData();
      });
    }
  });
};

//#endregion

const getData = async function () {
  let res = await getRole();
  tableData.length = 0;
  tableData.push(...res.data.data);

  // 菜单数据

};

const deleteData = async function (id: string | number) {
  await deleteRole(id);
  getData();
};

const deleteDatas = async function () {
  let deleteid = [];
  for (let i = 0; i < selectRow.length; i++) {
    deleteid.push(selectRow[i].id);
  }
  await deleteRole(deleteid.toString());
  getData();
};

const changeshow = ref(false);
const changeform = reactive<Ruleform>({
  rolename: "",
  status: 1,
  remark: "",
  description: "",
});
const changeformref = ref<FormInstance>();
const changerules = reactive<FormRules<Ruleform>>({});
const changeid = ref();
const changeData = async function (formref: FormInstance | undefined) {
  if (!formref) return;
  await formref.validate((valid) => {
    if (valid) {
      changeshow.value = false;
      let data: any = {};
      if (changeform.rolename) {
        data["rolename"] = changeform.rolename;
      }
      if (changeform.remark) {
        data["remark"] = changeform.remark;
      }
      if (changeform.status) {
        data["status"] = changeform.status;
      }
      if (changeform.description) {
        data["description"] = changeform.description;
      }
      putRole(changeid.value, data).then((res) => {
        console.log(res);
        getData();
      });
    }
  });
};

/////////////////////////////////////////////////////////
//  权限
const roleshow = ref(false);
const roleid = ref(0);
const tree = ref<TreeInstance>();
const menutree= reactive<any[]>([]);
const defaultkey = reactive<number[]>([])
const selecttree = reactive<any[]>([]);
const handleCheckChange = function (data: any, checked: boolean) {
  if (checked) {
    selecttree.push(data.id as string);
  } else {
    if (selecttree.indexOf(data.id) >= 0) {
      selecttree.splice(selecttree.indexOf(data.id), 1);
    }
  }
  console.log(data,selecttree);
};

const halfnode = reactive<any[]>([]);
const buildTree = function (items: any[], pid = 0) {
  //查找pid子节点
  let pitems = items.filter((s) => s.pid == pid);
  if (!pitems || pitems.length <= 0) return null;
  //递归
  pitems.forEach((item) => {
    const res = buildTree(items, item.id);
    if (res && res.length > 0) {
      item.children = res;
      halfnode.push(item.id)
    }
  });
  return pitems;
};

const showroledialog = async function(id:string|number) {
  roleid.value = Number(id);
  menutree.length = 0
  selecttree.length = 0
  defaultkey.length = 0
  let res = await getResources();
  let menus = [];
  for (let i = 0; i < res.data.data.length; i++) {
    menus.push({
      id: Number(res.data.data[i].id),
      pid: Number(res.data.data[i].pid),
      label: res.data.data[i].menu_name,
    });
  }
  let data = buildTree(menus, 1);
  menutree.push(...data as any[])
  nextTick(async function(){
    
    res = await getRoleResources(id);
    console.log(halfnode,res.data.data)
    if(res.data.data.length&& res.data.data.length>0){
      res.data.data.forEach((e:any)=>{
        if(!(halfnode.indexOf(Number(e.mid))>=0)){
          defaultkey.push(Number(e.mid))
        }
      })
      console.log(defaultkey)
    }
    tree.value?.setCheckedKeys(defaultkey,false)
    roleshow.value = true;
  });

}
const changeRole = async function() {
  let allhalfnode = tree.value?.getHalfCheckedKeys();
  selecttree.push(...allhalfnode as number[])
  await putRoleResources(roleid.value,selecttree)
  // console.log(res);
  roleshow.value = false
  
}

</script>

<template>
  <div class="role">
    <div class="tablebtn">
      <el-button size="small" type="primary" @click="addshow = true" v-if="route.meta.add"
        >新增</el-button
      >
      <el-button size="small" type="danger" @click="deleteDatas" v-if="route.meta.deletes"
        >批量删除</el-button
      >
    </div>
    <div style="width: 100%; height: calc(100% - 70px)">
      <el-table
        :data="tableData"
        ref="eltable"
        style="width: 100; height: 100%"
        stripe
        border
        highlight-current-row
        table-layout="auto"
        size="small"
        @selection-change="getSelectionRows"
      >
        <el-table-column
          fixed
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="角色名称" prop="rolename"></el-table-column>
        <el-table-column label="英文标识" prop="remark"></el-table-column>
        <el-table-column label="角色描述" prop="description"></el-table-column>
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-button
              disabled
              size="small"
              :type="scope.row.status == 1 ? 'primary' : 'warning'"
            >
              {{ scope.row.status == 1 ? "启用" : "禁用" }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button
              size="small"
              @click="showroledialog(scope.row.id)" v-if="route.meta.auth"
              >权限</el-button
            >
            <el-button
              size="small"
              @click="
                () => {
                  changeshow = true;
                  changeid = scope.row.id;
                }
              "
              v-if="route.meta.update"
              >修改</el-button
            >
            <el-button size="small" @click="deleteData(scope.row.id)" v-if="route.meta.delete">
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="tablepag" v-if="false">
      <el-pagination
        small
        background
        layout="prev, pager, next"
        :total="50"
        class="mt-4"
      />
    </div>

    <el-dialog v-model="addshow" draggable>
      <template #header> 新增 </template>
      <el-form :label-width="100" :model="form" :rules="rules" ref="formref">
        <inputtext
          label="角色名称"
          prop="rolename"
          v-model="form.rolename"
        ></inputtext>
        <inputtext
          label="英文标识"
          prop="remark"
          v-model="form.remark"
        ></inputtext>
        <inputradio
          label="状态"
          prop="status"
          :radio="[
            { label: 1, text: '启用' },
            { label: 2, text: '禁用' },
          ]"
          v-model="form.status"
        ></inputradio>
        <inputtext
          label="角色描述"
          prop="description"
          v-model="form.description"
        ></inputtext>
      </el-form>
      <template #footer>
        <el-button @click="addData(formref)" >新增</el-button>
        <el-button @click="addshow = false">取消</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="changeshow" draggable>
      <template #header> 新增 </template>
      <el-form
        :label-width="100"
        :model="changeform"
        :rules="changerules"
        ref="changeformref"
      >
        <inputtext
          label="角色名称"
          prop="rolename"
          v-model="changeform.rolename"
        ></inputtext>
        <inputtext
          label="英文标识"
          prop="remark"
          v-model="changeform.remark"
        ></inputtext>
        <inputradio
          label="状态"
          prop="status"
          :radio="[
            { label: 1, text: '启用' },
            { label: 2, text: '禁用' },
          ]"
          v-model="changeform.status"
        ></inputradio>
        <inputtext
          label="角色描述"
          prop="description"
          v-model="changeform.description"
        ></inputtext>
      </el-form>
      <template #footer>
        <el-button @click="changeData(changeformref)">新增</el-button>
        <el-button @click="changeshow = false">取消</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="roleshow">
      <template #header> 权限控制 </template>
      <el-tree
        ref="tree"
        :data="menutree"
        show-checkbox
        @check-change="handleCheckChange"
        default-expand-all
        node-key="id"
        :default-checked-keys="defaultkey"
        :check-strictly="false"
      ></el-tree>
      <template #footer>
        <el-button @click="changeRole">确认</el-button>
        <el-button @click="roleshow = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style>
.role {
  width: 100%;
  height: 100%;
}
.tablebtn {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  background: rgba(123, 123, 123, 0.2);
  padding-left: 20px;
  box-sizing: border-box;
}
.tablepag {
  width: 100%;
  height: 30px;
  background: rgba(123, 123, 123, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
